package project.action;

import org.json.JSONException;
import org.json.JSONObject;
import project.Dao.TaskDao;
import project.Dao.UserDao;
import project.Dao.groupDao;
import project.Domain.GroupClass;
import project.Domain.ID_Name;
import project.Domain.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.System.out;

public class action extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doGet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doPost");
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("执行了service");
        try {
            processAEdFile(request, response);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void processAEdFile(HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException {
        request.setCharacterEncoding("UTF-8");
//        获取操作方式增删改
        JSONObject json = new JSONObject();
        String action = request.getParameter("action");

        out.println("收到的指令:"+action);
        /////////////获取组长是否建组，组员是否入组信息
        if(action.equals("refresh")){
            String userName = request.getParameter("userName");
            String role = request.getParameter("userRole");
            String id = request.getParameter("userID");
            out.println("账号名：" + userName+"角色："+role);
            if(role.equals("组员")){
                UserDao userDao = new UserDao();
                if(userDao.getLeaderID(userName) != -1){
                    json.put("msg", "yes");
                }
                else json.put("msg", "no");
            }
           else if(role.equals("组长")){
               groupDao group_Dao = new groupDao();
               List<ID_Name> list = group_Dao.getGroup(Integer.parseInt(id));
               if(list.size()!=0)   json.put("msg", "yes");
               else json.put("msg", "no");
            }
        }
        //////////获取全部项目组的基本信息（名称，经理）以供组员选择
        else if(action.equals("get_project_list")){
            groupDao group_Dao = new groupDao();
            List<ID_Name> list = group_Dao.getID_Name();
            List jsonList = new ArrayList();
            for(int i = 0; i < list.size(); i ++){
                Map map = new HashMap();
                map.put("id", list.get(i).getId());
                map.put("projectName",list.get(i).getProjectName());
                map.put("leaderName",list.get(i).getLeaderName());
                jsonList.add(map);
            }
            json.put("result", 1);
            json.put("aaData", jsonList);
        }
        //////////////组员加入项目/
        else if(action.equals("join_project")){
            String leaderID = request.getParameter("leaderID");
            String memberID = request.getParameter("memberID");
            out.println("申请账户id："+memberID);
            UserDao userDao = new UserDao();
            if(userDao.updateLeaderID(Integer.parseInt(leaderID), Integer.parseInt(memberID)))
            {
                json.put("result", 1);
            }
            else json.put("result", 0);
        }
        //////////////查询个人信息返回修改界面/
        else if(action.equals("get_profile")){
            String userName = request.getParameter("userName");
            out.println("账户名："+userName);
            UserDao userDao = new UserDao();
            //获取账户全部个人信息；
            User user = userDao.login(userName);
            if(user != null){
                out.println(user.toString());
                json.put("result", 1);
                // 创建List 对象，封装数据返回
                List jsonList = new ArrayList();
                Map map = new HashMap();
                map.put("id", user.getId());
                map.put("user_name", user.getName());
                map.put("login_name", user.getUsername());
                map.put("user_email", user.getEmail());
                map.put("user_mobile", user.getMobile());
                map.put("user_role", user.getRole());
                map.put("password", user.getPassword());
                if(user.getLeaderID() == 0){
                    map.put("project_name", "暂未获得您的项目信息");
                    map.put("leader_name", "暂未获得您的项目信息");
                }
                else {
                    if(user.getRole().equals("组长")){
                        groupDao group_Dao = new groupDao();
                        List<ID_Name> list = group_Dao.getGroup(user.getId());
                        if(list.size()==0){
                            map.put("project_name", "暂未获得您的项目信息");
                            map.put("leader_name", "暂未获得您的项目信息");
                        }else{
                            map.put("project_name", list.get(0).getProjectName());
                            map.put("leader_name", list.get(0).getLeaderName());
                        }
                    }
                    else {
                        groupDao group_Dao = new groupDao();
                        ID_Name temp = group_Dao.getGroup(user.getLeaderID()).get(0);
                        map.put("project_name", temp.getProjectName());
                        map.put("leader_name", temp.getLeaderName());
                    }
                }
                jsonList.add(map);
                json.put("profile", jsonList);

            }
            else {
                json.put("result", 0);
            }
        }
        //////////////修改基本信息/
        else if(action.equals("save1")){
            String id = request.getParameter("id");
            String user_name = request.getParameter("user_name");
            String mobile = request.getParameter("mobile");
            String email = request.getParameter("email");
            String login_name = request.getParameter("login_name");
            out.println("账户id："+id);
            UserDao userDao = new UserDao();
            User userEdit = new User(Integer.parseInt(id), user_name, email, mobile, null, login_name, null);
            if(userDao.edit1(userEdit)){
                json.put("result", 1);
            }
            else json.put("result", 0);
        }
        //////////////修改密码/
        else if(action.equals("save2")){
            String login_name = request.getParameter("login_name");
            String old_password = request.getParameter("old_password");
            String new_password = request.getParameter("new_password");
            out.println("账户名："+login_name);
            UserDao userDao = new UserDao();
            User user = userDao.login(login_name);

            if (user != null) {
                if(!user.getPassword().equals(old_password)){
                    json.put("result", 0);
                    json.put("fail_reason", "旧密码错误！");
                }else {
                    user.setPassword(new_password);
                    if(userDao.updatePassword(user.getId(),user.getPassword())){
                        json.put("result", 1);
                    }else {
                        json.put("result", 0);
                        json.put("fail_reason", "出现未知错误！");
                    }
                }
            }
            else{
                json.put("result", 0);
                json.put("fail_reason", "用户不存在！");
            }
        }
        //////////////注销账号/
        else if(action.equals("delete_user")){
            String id = request.getParameter("id");
            String login_name = request.getParameter("login_name");
            String password = request.getParameter("password");
            String role = request.getParameter("role");
            out.println("账户名："+login_name);
            UserDao userDao = new UserDao();
            User user = userDao.login(login_name);

            if (user != null) {
                if(!user.getPassword().equals(password)){
                    json.put("result", 0);
                    json.put("fail_reason", "密码错误！");
                }else {
                    if(role.equals("组员")){
                        if(userDao.delete(Integer.parseInt(id))){
                            TaskDao taskDao = new TaskDao();
                            taskDao.deleteMember(Integer.parseInt(id));
                            json.put("result", 1);
                        }else {
                            json.put("result", 0);
                            json.put("fail_reason", "出现未知错误！（可能已注销成功，请刷新）");
                        }
                    }
                    if(role.equals("组长")){
                        groupDao group_Dao = new groupDao();
                        if(userDao.delete(Integer.parseInt(id))){
                            group_Dao.deleteProperty(Integer.parseInt(id));
                            userDao.setLeaderIDNull(Integer.parseInt(id));
                            group_Dao.delete(Integer.parseInt(id));
                            TaskDao taskDao = new TaskDao();
                            taskDao.deleteLeader(Integer.parseInt(id));
                            json.put("result", 1);
                        }else {
                            json.put("result", 0);
                            json.put("fail_reason", "出现未知错误！（可能已注销成功，请刷新）");
                        }
                    }
                }
            }
            else{
                json.put("result", 0);
                json.put("fail_reason", "用户不存在！");
            }
        }
        //////////////退出项目/
        else if(action.equals("quit_project")){
            String id = request.getParameter("id");
            String login_name = request.getParameter("login_name");
            String password = request.getParameter("password");
            String role = request.getParameter("role");
            out.println("账户名："+login_name);

            UserDao userDao = new UserDao();
            User user = userDao.login(login_name);

            if (user != null) {
                if(!user.getPassword().equals(password)){
                    json.put("result", 0);
                    json.put("fail_reason", "密码错误！");
                }else {
                    if(role.equals("组员")){
                        user.setLeaderID(0);
                        if(userDao.edit3(user)){
                            TaskDao taskDao = new TaskDao();
                            taskDao.deleteMember(Integer.parseInt(id));
                            json.put("result", 1);
                        }else {
                            json.put("result", 0);
                            json.put("fail_reason", "出现未知错误！");
                        }
                    }
                    if(role.equals("组长")){
                        user.setLeaderID(1);
                        groupDao group_Dao = new groupDao();
                        if(userDao.edit3(user) && group_Dao.delete(Integer.parseInt(id)) &&userDao.setLeaderIDNull(Integer.parseInt(id))){
                            TaskDao taskDao = new TaskDao();
                            taskDao.deleteLeader(Integer.parseInt(id));
                            group_Dao.deleteProperty(Integer.parseInt(id));
                            json.put("result", 1);
                        }else {
                            json.put("result", 0);
                            json.put("fail_reason", "出现未知错误！（可能已退出成功，请刷新）");
                        }
                    }
                }
            }
            else{
                json.put("result", 0);
                json.put("fail_reason", "用户不存在！");
            }
        }

        ////////////////////////获取全部项目组的全部信息以供管理员选择
        else if(action.equals("get_project_info")){
            String user_role = request.getParameter("user_role");
            String id = request.getParameter("user_id");
            groupDao group_Dao = new groupDao();
            List<GroupClass> projectList = new ArrayList<>();
            switch (user_role){
                case "组长":
//                查询该组的项目
                    projectList = group_Dao.getIndexGroup(Integer.parseInt(id));
                    break;
                case "管理员":
//                查询全部项目
                    projectList = group_Dao.getGroupList();
                    break;
            }
            out.println(projectList);
//      创建List 对象，封装数据返回
            List jsonList = new ArrayList();
            for (GroupClass project : projectList) {
                Map map = new HashMap();
                map.put("id", project.getLeaderID());
                map.put("project_name", project.getName());
                map.put("leader_name", project.getLeaderName());
                map.put("property", project.getProperty());
                map.put("start_time", project.getStartTime());
                map.put("due_time", project.getDueTime());
                map.put("workload", project.getWorkload());
                map.put("progress", project.getProgress());
                jsonList.add(map);
            }
            json.put("project_list", jsonList);
            json.put("result_msg", "ok");
            json.put("result_code", 0);
        }
        //将响应消息返回页面
        out.println("最后构造得到的json是:"+json);
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();
    }
}